#pragma once

class FilterResonance
{
	double fb = 0;
	double buf0 = 0.0;
	double buf1 = 0.0;

	// 2.0 = 22050 KHz;
	// 1.0 = 44100 KHz;
	// 0.5 = 88200 KHz;
	double m_bitrateType = 1.0; // 44100;
public:
	double Res = 0.8;
	double Cutoff;

	void Reset()
	{
		buf0 = 0.0;
		buf1 = 0.0;
		Cutoff = 0.9;
	}

	void SetBitrate(double bitrate)
	{
		m_bitrateType = 44100.0 / bitrate;
	}

	/// <summary>
	/// Based on the Resonant filter algorithm originally posted by Paul Kellett.
	/// Source: http://www.musicdsp.org/showArchiveComment.php?ArchiveID=29
	/// </summary>
	/// <param name="input"></param>
	/// <param name="output"></param>
	void ProcessTime(double* input, double* output, int length)
	{
		if (Cutoff < 0.0001)
			Cutoff = 0.0001;

		double cutoff = Cutoff;
		double res = Res;
		double _fb = fb;
		double _buf0 = buf0;
		double _buf1 = buf1;

		// Set feedback amount given f and q between 0 and 1.
		for (int i = 0; i < length; ++i)
		{
			// Set feedback amount given f and q between 0 and 1.
			_fb = res + res / (1.0 - cutoff);

			_buf0 = _buf0 + cutoff * (input[i] - _buf0 + _fb * (_buf0 - _buf1));
			_buf1 = _buf1 + cutoff * (_buf0 - _buf1);
			output[i] = _buf1;
		}
		fb = _fb;
		buf0 = _buf0;
		buf1 = _buf1;
	}
};